import router from './router'
import { useUserStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import instance from '@/service/request'

NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
})

router.beforeEach(async (to, from) => {
  if (to.path !== from.path) {
    NProgress.start()
  }
  const userStore = useUserStore()
  const { isLogin, token } = userStore
  const { redirectAlreadyLogin, requiredLogin, title } = to.meta
  if (title) {
    document.title = title as string
  }

  if (!isLogin) {
    if (token && to.path !== '/login') {
      instance.defaults.headers.common['Authorization'] = `Bearer ${token}`
      try {
        await userStore.fetchCurrentUser()
        if (redirectAlreadyLogin) {
          return '/'
        }
      } catch (error) {
        return '/login'
      }
    } else {
      if (requiredLogin) {
        return '/login'
      }
    }
  } else {
    if (redirectAlreadyLogin) {
      return '/'
    }
    // 如果什么都不返回，则导航是有效的
  }
})

router.afterEach(() => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})
